/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import job.WorkConnection;

/**
 *
 * @author Andrea
 */
public class ConnectionsManager implements Closeable, Observer {

    private final ServerSocket ss;

    private final List<Connection> connections;

    private final Thread connectionCycle;

    public ConnectionsManager() throws IOException {
        this.ss = new ServerSocket(7777);

        connections = new ArrayList<>(20);

        System.out.println("opened the server");

        connectionCycle = new Thread("Connections cycle") {

            @Override
            @SuppressWarnings("SleepWhileInLoop")
            public void run() {
                while (true) {
                    try {
                        Socket sock = ConnectionsManager.this.ss.accept();

                        System.out.println("new Connection at: " + sock.getInetAddress());

                        Connection c = new WorkConnection(sock);

                        connections.add(c);

                        c.addObserver(ConnectionsManager.this);

                        c.start();
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    } catch (IOException ex) {
                        Logger.getLogger(ConnectionsManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };
    }

    public void start() {
        connectionCycle.start();
    }

    @Override
    public void close() throws IOException {
        ss.close();

        for (Connection connection : connections) {
            connection.close();

            connections.remove(connection);
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof Connection) {
            connections.remove((Connection) o);
        }
        throw new IllegalArgumentException("this function is called by a connection, if you aren't a connection you shouldn't call this");
    }

    public static void main(String[] args) throws IOException {
        ConnectionsManager cm = new ConnectionsManager();

        cm.start();
    }
}
